import React, { Component } from 'react';
import { ImageBackground, ScrollView, View, Image, StatusBar, Text, TouchableOpacity, FlatList, RefreshControl, DeviceEventEmitter } from 'react-native';
import TabBarTitle from '../components/TabBarTitle';
import { TabBarImage, TabBarAnimationImage } from '../components/TabBarImage';
import Colors from '../constants/Colors';
import { statusBarHeight, titleHeight, width, unitWidth } from '../constants/AdapterUtil';
import { MyHeader } from '../components/MyHeader';
import { SubmitButton8, AddButton, ReduceButton, SubmitButton9 } from '../components/Button';
import { api_member_cart_get_list, api_order_create, api_member_address, api_order_create_submit, api_order_pay } from '../constants/HttpServices';
import { postFetch } from '../constants/HttpExtension';
import MyListView from '../components/MyListView';
import { DeleteTextView } from '../components/MyTextView';
import { CommonModal2, BottomPayModal, CommonModal3, BottomAddressChooseModal } from '../components/Modal';
import { MeItem } from '../components/Item';
import { MyInput1 } from '../components/Input';
import TextUtil from '../constants/TextUtil';
import { show } from '../constants/Toast';
import { contactBrowser } from '../constants/Gobrowser';
import { wxPay } from '../constants/Pay';

export default class ConfirmOrderScreen extends Component {
    constructor(props) {
        super(props)
        this.id = this.props.navigation.getParam('id', -1)
        this.count = this.props.navigation.getParam('count', -1)
        this.state = {
            userInfo: {},
            list: [],
            addressList: [],
            currentChooseAddressIndex: 0,

            user_type: global.userInfo.user_type,

            address: '',
            receiver_mobile: '',
            receiver_name: '',
            province: '',
            city: '',
            area: '',

            mobile: '',//代付手机号

            realprice: '0',
            total: '0',
            dispatch_price: 0//运费
        }
    }

    componentDidMount() {
        this.props.navigation.addListener('didFocus', payload => {
            this.refs.MyListView.onRefresh();
            this.getAddress()
        })
    }

    render() {
        return (
            <View style={{ flex: 1, backgroundColor: Colors.colorF7 }}>
                <MyHeader title='确认订单' leftImg={require('../res/ic_arrow_left.png')} leftClick={() => { this.props.navigation.pop() }} />
                <MyListView
                    style={{ marginBottom: 50 * unitWidth, }}
                    ref='MyListView'
                    ListHeaderComponent={
                        <View>
                            <MeItem
                                icon={
                                    <Image source={require('../res/syss_dddw.png')} style={{ width: 16 * unitWidth, height: 20 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                } text={this.state.address ? (this.state.address + '     ' + this.state.receiver_name + '     ' + this.state.receiver_mobile) : ''} isLast={false}
                                onPress={() => {
                                    // this.props.navigation.navigate('AddAddress', {
                                    //     onSuccess: (data) => {
                                    //         this.setState({
                                    //             address: data.address,
                                    //             receiver_mobile: data.mobile,
                                    //             receiver_name: data.name,
                                    //             province: data.province,
                                    //             city: data.city,
                                    //             area: data.area,
                                    //         })
                                    //     },
                                    //     data: {
                                    //         address: this.state.address,
                                    //         mobile: this.state.receiver_mobile,
                                    //         name: this.state.receiver_name,
                                    //         province: this.state.province,
                                    //         city: this.state.city,
                                    //         area: this.state.area,
                                    //     }
                                    // })
                                    this.refs.BottomAddressChooseModal.showModal();
                                }} />
                            <View style={{ minHeight: 50 * unitWidth, backgroundColor: Colors.white, marginTop: 5 * unitWidth }} >
                                <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                                    <Image source={require('../res/gwc_spxqgwc.png')} style={{ width: 17 * unitWidth, height: 17 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                    <Text style={{ color: Colors.black, fontSize: 14 * unitWidth, marginLeft: 15 * unitWidth }}>商品详情</Text>
                                </View>
                                <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                            </View>
                            {/* {this.state.user_type == '3' ?
                                <View style={{ minHeight: 50 * unitWidth, backgroundColor: Colors.white, marginTop: 5 * unitWidth }} >
                                    <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                                        <Image source={require('../res/gwc_zrdfic.png')} style={{ width: 17 * unitWidth, height: 18 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                                        <Text style={{ color: Colors.black, fontSize: 14 * unitWidth, marginLeft: 15 * unitWidth }}>找人代付</Text>
                                    </View>
                                    <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                                </View> : null} */}
                        </View>
                    }
                    // ListFooterComponent={
                    //     global.userInfo.user_type == '3' ?
                    //         <View style={{ backgroundColor: Colors.white, marginTop: 5 * unitWidth }} >
                    //             <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1, marginVertical: 10 * unitWidth }}>
                    //                 <Image source={require('../res/gwc_zrdfic.png')} style={{ width: 17 * unitWidth, height: 18 * unitWidth, marginLeft: 20 * unitWidth }} resizeMode='stretch' />
                    //                 <Text style={{ color: Colors.black, fontSize: 14 * unitWidth, marginLeft: 15 * unitWidth }}>找人代付</Text>
                    //             </View>
                    //             <View style={{ backgroundColor: Colors.colorEF, width: width, alignSelf: 'center', height: 0.5, marginTop: 10 * unitWidth, position: 'absolute', bottom: 0 }} />
                    //             <MyInput1
                    //                 style={{ marginTop: 0 * unitWidth }}
                    //                 onChangeText={(text) => { this.setState({ mobile: TextUtil.getTextInput(text, 1) }) }}
                    //                 title={
                    //                     <Text style={{ color: Colors.black, fontSize: 15 }}>*手机号：</Text>
                    //                 }
                    //                 maxLength={11}
                    //                 placeholder='请输入手机号'
                    //                 value={this.state.mobile} isLast={true} />
                    //         </View> : null
                    // }
                    list={this.state.list}
                    renderItem={this.getItem.bind(this)}
                    getList={this.getData.bind(this)}
                />
                <View style={{
                    flexDirection: 'row', position: 'absolute', bottom: 0,
                    alignItems: 'center', width: width, height: 50 * unitWidth
                }}>
                    <View style={{ flex: 2.5, alignItems: 'center', justifyContent: 'center' }}>
                        <Text style={{ fontSize: 14, color: Colors.black }}>共{this.state.total}件 , 合计:<Text style={{ color: Colors.colorRed }}>￥{this.state.realprice + `(运费${this.state.dispatch_price}元)`}</Text></Text>
                    </View>
                    <View style={{ flex: 1.2, alignItems: 'flex-start', justifyContent: 'center' }}>
                        <SubmitButton8 text='提交订单' onPress={() => {
                            let goods = []
                            for (let x of this.state.list) {
                                for (let y of x.goods) {
                                    goods.push({
                                        goodsid: y.goodsid,
                                        total: y.total
                                    })
                                }
                            }
                            this.submitOrder(goods)
                        }} />
                    </View>
                </View>
                <CommonModal3 ref='CommonModal3' title={'恭喜你提交订单成功\n快快提醒朋友代付'} btnText='我知道了'
                    onPress={() => {
                        this.props.navigation.pop();
                    }}
                    onClosePress={() => {
                        this.props.navigation.pop();
                    }} />
                <BottomPayModal ref='BottomPayModal' onClick={(index) => {
                    this.payOrder(index)
                }} />
                <BottomAddressChooseModal ref='BottomAddressChooseModal'
                    currentChooseAddressIndex={this.state.currentChooseAddressIndex}
                    addressList={this.state.addressList} onChoose={(item, index) => {
                        this.setState({
                            receiver_mobile: item.mobile,
                            receiver_name: item.realname,
                            province: item.province,
                            city: item.city,
                            area: item.area,
                            address: item.address,
                            currentChooseAddressIndex: index,
                        })
                    }} />
            </View>
        )
    }

    getItem({ item, index }) {
        return (
            <View style={{ alignItems: 'center' }}>
                <View style={{
                    minHeight: 150 * unitWidth,
                    backgroundColor: Colors.white, marginBottom: 8 * unitWidth, paddingHorizontal: 8 * unitWidth
                }}>
                    <View style={{ height: 40 * unitWidth, flexDirection: 'row', alignItems: 'center' }}>
                        <Image style={{
                            width: 12 * unitWidth, height: 11 * unitWidth, marginLeft: 10 * unitWidth
                        }}
                            source={require('../res/gwc_gs.png')} resizeMode='stretch' />
                        <Text style={{ fontSize: 14, color: Colors.black, marginLeft: 5 * unitWidth }}>{item.shopname}</Text>
                        <Image style={{
                            width: 5 * unitWidth, height: 10 * unitWidth, position: 'absolute', right: 0 * unitWidth,
                        }}
                            source={require('../res/me_back.png')} resizeMode='stretch' />
                    </View>
                    <View style={{ backgroundColor: Colors.colorEF, width: 350 * unitWidth, alignSelf: 'center', height: 0.5, }} />
                    <View>
                        {this.getGoodsView(item.goods, index)}
                    </View>
                </View>
            </View>
        )
    }

    getGoodsView(list, index) {
        let views = []
        for (let i = 0, len = list.length; i < len; i++) {
            let item = list[i];
            views.push(
                <View style={{ height: 109 * unitWidth, flexDirection: 'row', alignItems: 'center' }}>
                    <Image style={{
                        width: 110 * unitWidth, height: 80 * unitWidth, marginLeft: 9 * unitWidth
                    }}
                        source={{ uri: item.thumb }} resizeMode='stretch' />
                    <View style={{ marginLeft: 10 * unitWidth }}>
                        <Text style={{ color: Colors.black, fontSize: 14, marginVertical: 4 * unitWidth, width: 190 * unitWidth }}>{item.title}</Text>
                        <View style={{
                            paddingHorizontal: 7 * unitWidth, borderWidth: 0.5, marginTop: 5 * unitWidth,
                            borderColor: Colors.colorRed, borderRadius: 5, alignSelf: 'flex-start'
                        }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 10, }}>线下价格:￥{item.offlineprice}</Text>
                        </View>
                        <View style={{ alignSelf: 'flex-start', marginTop: 2 * unitWidth, flexDirection: 'row', alignItems: 'center', width: 190 * unitWidth }}>
                            <Text style={{ color: Colors.colorRed, fontSize: 17, }}>￥{item.marketprice}</Text>
                            <DeleteTextView text={'￥' + item.productprice} style={{ marginLeft: 3 * unitWidth }} />
                            <Text style={{ color: Colors.black, fontSize: 17, position: 'absolute', right: 0 * unitWidth }}>x{item.total}</Text>
                        </View>
                    </View>
                </View>
            );
        }
        return views
    }

    getData(page) {
        let params = {
            // page: page
        }
        if (this.id != -1) {
            params['id'] = this.id
            params['total'] = this.count
        }
        postFetch(api_order_create, params, {
            success: (response) => {
                if (page == 1) {
                    this.setState({
                        list: response.result.goods_list,
                        realprice: response.result.realprice,
                        total: response.result.total,
                        dispatch_price: response.result.dispatch_price,
                    }, () => {
                        this.refs.MyListView.onHasMore();
                    })
                } else {
                    if (response.result.goods_list && response.result.goods_list.length > 0) {
                        this.setState({
                            list: this.state.list.concat(response.result.goods_list),
                            realprice: response.result.realprice,
                            total: response.result.total
                        }, () => {
                            this.refs.MyListView.onHasMore();
                        })
                    } else {
                        this.refs.MyListView.onNoMore();
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //获取地址
    getAddress() {
        let params = {

        }
        postFetch(api_member_address, params, {
            success: (response) => {

                for (let i = 0, len = response.result.list.length; i < len; i++) {
                    let item = response.result.list[i]
                    if (item.isdefault == '1') {
                        this.setState({
                            addressList: response.result.list,
                            receiver_mobile: item.mobile,
                            receiver_name: item.realname,
                            province: item.province,
                            city: item.city,
                            area: item.area,
                            address: item.address,
                            currentChooseAddressIndex: i
                        })
                        break
                    }
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //下单
    submitOrder(goods) {
        if (this.state.addressList && this.state.addressList.length == 0) {
            show('请添加地址')
            return
        }

        let params = {
            goods: goods,
            addressid: this.state.addressList[this.state.currentChooseAddressIndex].id,
            submit: true,
            fromcart: '1'
        }
        postFetch(api_order_create_submit, params, {
            success: (response) => {
                if (global.userInfo.user_type == '3') {
                    this.refs.CommonModal3.showModal();
                } else {
                    this.orderId = response.result.orderid
                    this.refs.BottomPayModal.showModal();
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }

    //支付订单
    payOrder(paytype) {
        let params = {
            id: this.orderId,
        }
        if (paytype == 1) {
            params['paytype'] = 'wechat'
        } else if (paytype == 2) {
            params['paytype'] = 'alipay'
        } else if (paytype == 3) {
            params['paytype'] = 'credit'
        }
        postFetch(api_order_pay, params, {
            success: (response) => {
                if (paytype == 1) {
                    wxPay(response.result.wechat, {
                        success: () => {
                            show('支付成功');
                            this.props.navigation.pop();
                        },
                        fail: () => {

                        }
                    })
                } else if (paytype == 2) {
                    contactBrowser(response.result.alipay.url)
                } else if (paytype == 3) {
                    show('支付成功');
                    this.props.navigation.pop();
                }
            },
            fail: (response) => {
                show(response.result.message);
            }
        })
    }
}